package com.bupt.liutong.admin.groupon.quartz;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

import org.dom4j.*;
import org.dom4j.io.*;
import org.springframework.beans.factory.annotation.Autowired;

import com.bupt.liutong.admin.core.base.CodeTableManager;
import com.bupt.liutong.admin.groupon.dao.GrouponDao;
import com.bupt.liutong.admin.groupon.dto.Groupon;
import com.bupt.liutong.admin.groupon.dto.Website;
import com.bupt.liutong.util.DateUtils;
import com.bupt.liutong.util.NumberUtils;
import com.bupt.liutong.util.StringUtils;

public class GetMeiTuanInfo implements GetGrouponInfo {

	@Autowired
	private GrouponDao grouponDao;

	public void execute(Website website) {
		SAXReader cityReader = new SAXReader();
		Document cityDoc;
		try {
			cityDoc = cityReader.read(new URL(website.getCityApi()));
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return;
		} catch (DocumentException e) {
			e.printStackTrace();
			return;
		}
		Element cityRoot = cityDoc.getRootElement();
		List<Element> cityList = cityRoot.selectNodes("//divisions/division");
		CodeTableManager ctm = CodeTableManager.getInstance();
		Map<String, String> cityKeyReverse = ctm.get("cityKeyReverse");
		// 循环所有城市
		for (Element city : cityList) {
			String cityKey = city.elementText("id");
			String cityId = cityKeyReverse.get(cityKey);
			if (StringUtils.isEmpty(cityId)) {
				// TODO log the city
				System.out.println(cityKey);
				continue;
			}
			SAXReader grouponReader = new SAXReader();
			Document grouponDoc;
			try {
				grouponDoc = grouponReader.read(new URL(website.getGrouponApi()
						.replace("${cityKey}", cityKey)));
			} catch (MalformedURLException e) {
				e.printStackTrace();
				continue;
			} catch (DocumentException e) {
				e.printStackTrace();
				continue;
			}
			Element grouponRoot = grouponDoc.getRootElement();
			List<Element> grouponList = grouponRoot.selectNodes("//deals/deal");
			// 循环当前城市所有优惠券
			for (Element grouponElement : grouponList) {
				Groupon groupon = new Groupon();
				groupon.setWebsiteId(website.getId());
				groupon.setCityId(Integer.valueOf(cityId));
				groupon.setLink(grouponElement.elementText("deal_url"));
				groupon.setTitle(grouponElement.elementText("title"));
				groupon.setSmallImageUrl(grouponElement.elementText("small_image_url"));
				groupon.setMediumImageUrl(grouponElement.elementText("medium_image_url"));
				groupon.setLargeImageUrl(grouponElement.elementText("large_image_url"));
				//groupon.setStartTime(grouponElement.elementText("start_date"));
				boolean soldout = Boolean.parseBoolean(grouponElement.elementText("sole_out"));
				groupon.setSoldout(NumberUtils.toInteger(soldout));
				groupon.setBought(Integer.parseInt(grouponElement.elementText("quantity_sold")));
				groupon.setPrice(Double.valueOf(grouponElement.elementText("price")));
				try{
					groupon.setValue(Double.valueOf(grouponElement.elementText("value")));
					groupon.setRebate(groupon.getPrice() / groupon.getValue() * 10);
				}catch(NumberFormatException e){
					//e.printStackTrace();
					System.out.println("value=" + grouponElement.elementText("value"));
				}
				
				
				String startTime = grouponElement.elementText("start_date");
				if (StringUtils.isEmpty(startTime)){
					System.out.println("startTime is empty");
					continue;
				}
				startTime = startTime.replace("T", "");
				startTime = startTime.substring(0, startTime.indexOf("+"));
				try {
					groupon.setStartTime(DateUtils.format(startTime, "yyyy-MM-ddHH:mm:ss"));
				} catch (ParseException e) {
					System.out.println("startTime="+grouponElement.elementText("start_date"));
				}
				
				String endTime = grouponElement.elementText("end_date");
				if (StringUtils.isEmpty(endTime)){
					System.out.println("endTime is empty");
					continue;
				}
				endTime = endTime.replace("T", "");
				endTime = endTime.substring(0, endTime.indexOf("+"));
				try {
					groupon.setEndTime(DateUtils.format(endTime, "yyyy-MM-ddHH:mm:ss"));
				} catch (ParseException e) {
					System.out.println("endTime="+grouponElement.elementText("end_date"));
				}

				Node conditions = grouponElement.selectSingleNode("conditions");
				String deadline = conditions.selectSingleNode("expiration_date").getText();
				if (StringUtils.isEmpty(deadline)){
					System.out.println("deadline is empty");
				} else {
					deadline = deadline.replace("T", "");
					deadline = deadline.substring(0, deadline.indexOf("+"));
					try {
						groupon.setDeadline(DateUtils.format(deadline, "yyyy-MM-ddHH:mm:ss"));
					} catch (ParseException e) {
						System.out.println("deadLine="+grouponElement.elementText("expiration_date"));
					}
				}
				groupon.setDes(conditions.selectSingleNode("details/detail").getText());
				groupon.setCreateTime(website.getBatchTime());
				
				Groupon duplicate = grouponDao.getDupGroupon(groupon);
				//System.out.println(groupon.getStartTime());
				//System.out.println(groupon.getEndTime());
				//System.out.println(groupon.getLink());
				if (duplicate == null || duplicate.getId() == null)
					grouponDao.insertGroupon(groupon);
			}
		}
	}

	public static void main(String[] args) {
	}

	public void setGrouponDao(GrouponDao grouponDao) {
		this.grouponDao = grouponDao;
	}
}
